<template>
  <div :class="{ 'ly-is-full': isFull }">
    <div class="tableSelect">
      <div v-show="searchMoreType">
        <screen :formInline="formInline" ref="RefScreen"></screen>
      </div>
      <el-form :inline="true" :model="formInline" label-position="right">
        <el-row :gutter="20" type="flex">
          <el-col :span="20">
            <el-form-item label="">
              <el-input
                v-model.trim="formInline.school_name"
                maxlength="60"
                clearable
                placeholder="学校名称"
                style="width: 200px"
              ></el-input>
              <el-button @click="search" type="primary" icon="Search"
                >查询</el-button
              ></el-form-item
            >
            <el-form-item label=""
              ><el-button @click="handleEdit('', 'reset')" icon="Refresh"
                >重置</el-button
              ></el-form-item
            >
            <el-form-item label=""
              ><el-button @click="exportText" type="primary"
                >导出</el-button
              ></el-form-item
            >
            <!-- <el-form-item label=""
                ><el-upload
                  class="upload-demo"
                  :on-preview="handlePreview"
                  :action="`${$config.API_URL}common/upload/`"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  accept=".xls,.xlsx"
                  :on-change="handleChange"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  :show-file-list="false"
                >
                  <el-button 
                  v-if="authority([1, 2])" 
                  type="primary">导入</el-button>
                </el-upload></el-form-item
              > -->
          </el-col>

          <!-- <el-form-item label-width="170">
            <el-button
              v-if="searchMoreType"
              @click="searchMore"
              type="primary"
              icon="Minus"
              style="margin-left: 20px"
              >收回查询</el-button
            >

            <el-button
              v-if="!searchMoreType"
              @click="searchMore"
              type="primary"
              icon="Aim"
              style="margin-left: 20px"
              >查询更多</el-button
            >
          </el-form-item> -->
        </el-row>

        <!-- <el-form-item label=""><el-button @click="handleDelete" type="danger" :disabled="multiple" v-show="isShowBtn('goodsType','商品分类','Delete')">删除</el-button></el-form-item> -->
      </el-form>
    </div>

    <div class="table">
      <el-table
        :height="tableHeight"
        border
        :data="tableData"
        v-loading="loadingPage"
        style="width: 100%"
        ref="tableref"
        @selection-change="handleSelectionChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!--                <el-table-column type="selection" width="55"></el-table-column>-->
        <el-table-column
          type="selection"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column type="index" width="60" align="center" label="序号">
          <template #default="scope">
            <span v-text="getIndex(scope.$index)"></span>
          </template>
        </el-table-column>
        <el-table-column min-width="200" max-width="200" label="设备状态">
          <template #default="scope">
            <div style="text-align: center">
              <el-button
                :type="
                  scope.row.is_wifistatus == 1 || scope.row.is_camerastatus == 1
                    ? 'primary'
                    : 'danger'
                "
                link
              >
                {{
                  scope.row.is_wifistatus == 1 || scope.row.is_camerastatus == 1
                    ? "正在使用中"
                    : "未使用"
                }}
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          min-width="100"
          prop="province"
          label="所在省份"
        ></el-table-column>
        <el-table-column
          min-width="100"
          prop="city"
          label="所在城市"
        ></el-table-column>
        <el-table-column
          min-width="100"
          prop="county"
          label="所在区县"
        ></el-table-column>
        <el-table-column
          min-width="200"
          prop="school_name"
          label="学校名称"
        ></el-table-column>
        <el-table-column
          min-width="200"
          prop="school_type"
          label="学校类别"
        ></el-table-column>
        <el-table-column
          min-width="100"
          prop="grade"
          label="年级"
        ></el-table-column>
        <el-table-column
          min-width="100"
          prop="class_name"
          label="班级"
        ></el-table-column>

        <el-table-column min-width="150" prop="user_name" label="在地工作人员">
        </el-table-column>
        <el-table-column min-width="150" max-width="300" label="是否提供摄像头">
          <template #default="scope">
            <div style="text-align: center">
              <p>{{ scope.row.is_camera }}</p>
              <el-link type="primary" @click="open(1, scope.row)">编辑</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="150" max-width="300" label="摄像头设备状态">
          <template #default="scope"> 
            <el-select
              v-model="scope.row.is_camerastatus"
              placeholder="暂未选择"
              style="width: 100px"
              @change="camersele1(1, scope.row, $event)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          min-width="150"
          max-width="300"
          label="是否提供随身WIFI"
        >
          <template #default="scope"> 
            <div style="text-align: center">
              <p>{{ scope.row.is_wifi }}</p>
              <el-link type="primary" @click="open(2, scope.row)">编辑</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="150" max-width="300" label="WIFI设备状态">
          <template #default="scope"> 

            <el-select
              v-model="scope.row.is_wifistatus"
              placeholder="暂未选择"
              style="width: 100px"
              @change="camersele1(2, scope.row, $event)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
  </div>
</template>
  <script>
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/Pagination.vue";
import { dateFormats } from "@/utils/util";
import "video.js/dist/video-js.css";
import {
  schoolList,
  adminGroup,
  schoolImport,
  rstaffschoolAdd,
  schoolUpdate,
} from "@/api/api";
import { lyMixins } from "@/mixins/mixins";
import dayjs from "dayjs";
import { setStorage, getStorage } from "@/utils/util";
import axios from "axios";
import screen from "@/components/screen/screen.vue";

export default {
  mixins: [lyMixins],
  components: {
    screen,
    Pagination,
  },
  name: "adminManage",
  data() {
    return {
      options: [
        { label: "使用中", value: "1" },
        { label: "停止使用", value: "2" },
        { label: "已丢失", value: "3" },
        { label: "丢失补发", value: "4" },
      ],
      videoDialogVisible: false,
      searchMoreType: false,
      fileList: [],
      videoList: [],
      inSchooleVis: false,
      inSchooleTextVis: false,
      isFull: false,
      loadingPage: false,
      // 选项框选中数组
      ids: [],

      // 选项框非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      formInline: {
        page: 1,
        page: 1,
        per_page: 10,
        school_name: "",
        director_name: "",
        director_phone: "",
        user_name: "",
        status: "",
      },
      pageparm: {
        page: 1,
        per_page: 10,
        total: 0,
      },
      images: "",
      userInfo: "", //用户权限字段
    };
  },
  methods: {
    camersele1(type, row, e) {
      let objs = { id: row.id, status: row.status };
      if (type == 1) objs.is_camerastatus = e;
      if (type == 2) objs.is_wifistatus = e;
      this.editShool(objs);
    },
    editShool(row) {
      let vm = this;

      schoolUpdate(row).then((res) => {
        ElMessage({
          type: "success",
          message: `${res.msg}`,
        });
        vm.getData();
      });
    },
    open(nums = 1, row) {
      let vm = this;
      ElMessageBox.prompt(
        `是否提供${nums == 1 ? "摄像头" : "随身WIFI"}`,
        `${nums == 1 ? "摄像头" : "WIFI"}`,
        {
          confirmButtonText: "提交",
          cancelButtonText: "取消",
          inputErrorMessage: "请输入您的内容",
          inputValue: row[nums == 1 ? "is_camera" : "is_wifi"],
        }
      ).then(({ value }) => {
        let objs = {
          id: row.id,
          status: row.status,
        };
        if (nums == 1) objs.is_camera = value;
        else objs.is_wifi = value;
        vm.editShool(objs);
      });
    },
    authority(groupArr = [0]) {
      // 权限筛选
      let userInfo = this.userInfo;
      // 当前权限和传来的权限组进行对比
      if (groupArr.some((item) => Number(item) === userInfo)) return true;
      return false;
    },
    rowUrl(url) {
      this.currentVideoUrl = url;
      this.videoDialogVisible = true; // 显示对话框
    },
    diaClose() {
      this.fileList = [];
      this.videoList = [];
    },
    searchMore() {
      this.searchMoreType = !this.searchMoreType;
    },
    handleEdit() {
      this.formInline.school_name = "";
      this.formInline = {
        page: 1,
        per_page: 10,
      };
      this.pageparm = {
        page: 1,
        per_page: 10,
        total: 0,
      };
      this.getData();
    },
    search(i, e) {
      this.formInline.page = 1;
      this.formInline.per_page = 10;
      let objs = this.$refs.RefScreen?.formInline || {};
      this.formInline = { ...this.formInline, ...objs };
      this.getData();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handlePreview(file) {
      console.log(file);
    },

    exportText(e) {
      if (this.ids.length == 0) {
        ElMessage.error("请先选择导出数据");
        return;
      }
      axios({
        url: this.$config.API_URL + "school/exports",
        method: "post", //请求方法
        responseType: "blob", //表示接受服务器返回的二进制流
        data: {
          id: this.ids,
        },
      })
        .then((res) => {
          console.log(res);

          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          let fileName = "设备记录"; // 自定义文件名
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // IE兼容
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            let objectUrl = (window.URL || window.webkitURL).createObjectURL(
              blob
            );
            let downloadLink = document.createElement("a");
            downloadLink.href = objectUrl;
            downloadLink.download = fileName;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            window.URL.revokeObjectURL(objectUrl); // 释放URL对象
          }
        })
        .catch((error) => {
          ElMessage.error("导出失败");
        });
    },
    handleAvatarSuccess(res, file) {
      this.fileList.push({
        name: res.data.url,
        url: res.data.url,
      });
    },
    handleAvatarSuccessVideo(res, file) {
      this.videoList.push({
        name: res.data.url,
        url: res.data.url,
      });
    },
    handleChangesImage(e) {},

    handleClose() {
      this.inSchooleVis = false;
      this.inSchooleTextVis = false;
    },
    submitData() {
      rstaffschoolAdd({ ...this.planForm }).then((res) => {
        if (res.code == 1) {
          ElMessage({
            showClose: true,
            message: "制定成功",
            type: "success",
          });
          this.getData();
          this.inSchooleVis = false;
        }
      });
    },

    planT(e) {
      this.planForm.status = this.inSchoolPlan.find(
        (item) => item.value == e
      ).value;
    },
    formatDateTime(time) {
      return dayjs.unix(time).format("YYYY-MM-DD HH:mm");
    },
    refreshData(x) {
      // 新增成功 搜索归0
      if (x) this.handleEdit("", "reset");
      else this.getData();
    },
    setFull() {
      this.isFull = !this.isFull;
      window.dispatchEvent(new Event("resize"));
    },
    // 表格序列号
    getIndex($index) {
      // (当前页 - 1) * 当前显示数据条数 + 当前行数据的索引 + 1
      return (this.pageparm.page - 1) * this.pageparm.per_page + $index + 1;
    },
    //多选项框被选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      console.log(this.ids, "选中项");
    },

    changeStatus(row) {
      console.log(row, "row----");
    },
    addModule(row) {
      // 普通全部新增
      console.log(this.GroupList, "---------新增出发");
      this.$refs.addModuleFlag.addModuleFn(row, "新增", this.GroupList);
    },

    callFather(parm) {
      this.formInline.page = parm.page;
      this.formInline.per_page = parm.per_page;
      this.getData();
    },
    //获取列表
    async getData() {
      this.loadingPage = true;
      this.formInline.status = 4; //通过

      schoolList(this.formInline).then((res) => {
        this.loadingPage = false;
        if (res.code == 1) {
          this.tableData = res.data.data;
          // // 将列表数据转换为树形数据
          // this.tableData = XEUtils.toArrayTree(res.data.data, { parentKey: 'parent', strict: false })
          this.pageparm.page = res.data.current_page;
          this.pageparm.per_page = res.data.per_page;
          this.pageparm.total = res.data.total;
        }
      });
    },

    timeChange(val) {
      if (val) {
        this.formInline.beginAt = dateFormats(val[0], "yyyy-MM-dd hh:mm:ss");
        this.formInline.endAt = dateFormats(val[1], "yyyy-MM-dd hh:mm:ss");
      } else {
        this.formInline.beginAt = null;
        this.formInline.endAt = null;
      }
      this.search();
    },
    getGroupList() {
      // 管理员分组获取
      adminGroup().then((res) => {
        if (res.code == 1) {
          //console.log(res, "------------成功获取到管理员分组列表");
          this.GroupList = res.data;
        }
      });
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter((item) => {
        return item.name != file.name;
      });
      console.log(this.fileList);
    },
    handleRemoveVideo(file, fileList) {
      this.videoList = this.videoList.filter((item) => {
        return item.name != file.name;
      });
      console.log(this.videoList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleSuccess(res, file) {
      if (res.code == 1) {
        schoolImport({ file: res.data.url }).then((res) => {
          if (res.code == 1) {
            this.getData();
            ElMessage.success(`导入成功`);
          } else {
            ElMessage.error(res.msg);
          }
        });
      }
    },
  },
  created() {
    this.userInfo = Number(JSON.parse(getStorage("groupId"))); //权限

    // 获取管理员分组
    this.getGroupList();
    // 数据获取
    this.getData();
  },
};
</script>
  
  <style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.video-box {
  width: 100%;
  max-width: 500px;
  max-height: 500px;
}
::v-deep .video-js .vjs-big-play-button {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
  